import React from "react";
import BaseScreen from "../BaseScreen";
import {upload} from '../../service/TaskService'
import { getTOKEN } from '../../utils/StorageUtil'
// 图片上传
class Upload  extends BaseScreen  {
    constructor(props) {
      super(props);
      this.imgurls=[]
      this.state = {
        imgurl: '',
        alertMsg: "",
        style:this.props.style,
        
      }
    }
    // 获取文件
    getFile = (e) => {
      var file = e.target.files[0]
      if (file.size > 1024*1024*5) {   
        this.showMsgDialog('图片太大无法上传，请选择小于5M的图片');      
        return
      }

      const files = Object.values(e.target.files)
      files.forEach((item,index)=>{
        this.uploadImg({
          token:getTOKEN(),
          file: item
        })
      })
      // base64
      // var reader = new FileReader()
      // reader.onload = function (e) {
      //   const result = this.result;    //data:base64
      //   that.props.getImgUrl(result)
      //   that.setState({
      //     style:{}
      //   })
      // };
      // reader.readAsDataURL(file);
    }
    getImgUrl = (e,func) => {
      const imgurl = e
      const image = new Image()
      // 获取图片宽高
      image.onload = function (e) {
        let width = this.width
        let height = this.height
        func(
          {
            imgurl: imgurl,
            width: width,
            height: height
          })
  
      }
      image.src = e
    }
  
    uploadImg =(params)=>{
      let {imgurls} = this.state
      upload(params)
      .then(

        res=>{
          this.getImgUrl(res.data.saved_files[0],this.props.setImgs)
        
        }
      ).catch(
        err=>{
          console.log(err)
        }
      )
    }
 
    render() {
      const {style} = this.props
      return (
        <div >
          {this.renderMsgDialog()}
          <input style={style}   ref={this.props.inputRef} type='file' accept="image/*" onChange={this.getFile} value={this.state.imgurl}/>
        </div>
      )
    }
  };
  
  
  const inputStyle = { border: 'none', outline: 'none' }
  export default Upload